#include "drawingview.h"
#include <QtOpenGL>
#include <Element>
#include <Document>
#include <StateManager>
#include "application.h"
#include "src/selection/selectionmanager.h"
#include <Core>
#include <Renderer>
#include <GridHelper>

DrawingView::DrawingView(QPointer<Document> doc, QWidget *parent) :
    QGLWidget(parent)
  , m_doc(doc)
{
    m_doc->setOwnerView(this);

    connect(m_doc, SIGNAL(elementAdded(QPointer<Element>)), this, SLOT(onElementAdded(QPointer<Element>)));
    connect(m_doc, SIGNAL(elementRemoved(QPointer<Element>)), this, SLOT(onElementRemoved(QPointer<Element>)));

    setMouseTracking(true);
    m_selectionManager = new SelectionManager(this);
    connect(m_selectionManager, SIGNAL(selectionChanged()),
            this, SLOT(updateGL()));

    m_gridHelper = new GridHelper(*doc, this);
}

QPointer<Document> DrawingView::document() const
{
    return m_doc;
}

void DrawingView::initializeGL()
{
    glClearColor(0, 0, 0, 255);
    glColor4f(1.0f, 1.0f, 1.0f, 1.0f);

    glDisable(GL_TEXTURE_2D);
}

void DrawingView::resizeGL(int w, int h)
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0f, w, h, 0.0, -1.0f, 1.0f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glViewport(0, 0, w, h);
}

void DrawingView::paintGL()
{
    glClear(GL_COLOR_BUFFER_BIT);

    glPushMatrix();
    glScalef(m_doc->zoom(), m_doc->zoom(), 1.0f);

    m_gridHelper->draw();

    m_selectionManager->drawSelectionMarkers();

    // draw elements
    foreach(QPointer<Element> element, m_doc->elements())
    {
        element->draw();
    }

    // handle drawing while tool creating new element
    QPointer<StateManager> sm = Application::app().toolsStateManager();
    Q_ASSERT(sm);
    sm->handleDraw();

    // draw selection rect on the top
    m_selectionManager->drawSelector();

    glPopMatrix();
}

void DrawingView::mousePressEvent(QMouseEvent *pEvent)
{
    QPointer<StateManager> sm = Application::app().toolsStateManager();
    Q_ASSERT(sm);
    sm->handleMousePressEvent(pEvent);
}

void DrawingView::mouseMoveEvent(QMouseEvent *pEvent)
{
    QPointer<StateManager> sm = Application::app().toolsStateManager();
    Q_ASSERT(sm);
    sm->handleMouseMoveEvent(pEvent);
}

void DrawingView::mouseReleaseEvent(QMouseEvent *pEvent)
{
    QPointer<StateManager> sm = Application::app().toolsStateManager();
    Q_ASSERT(sm);
    sm->handleMouseReleaseEvent(pEvent);
}

void DrawingView::onElementAdded(QPointer<Element> element)
{
    // OPTIMIZE: update with element rect
    update();
}

void DrawingView::onElementRemoved(QPointer<Element> element)
{
    // OPTIMIZE: update with element rect
    update();
}

QPointer<SelectionManager> DrawingView::selectionManager() const
{
    return m_selectionManager;
}


